package com.frxuexi.cart.view

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.cart.viewmodel.CartViewModel
import com.frxuexi.cart.R
import com.frxuexi.cart.adapter.MyCouponAdapter
import com.frxuexi.cart.adapter.PreOrderAdapter
import com.frxuexi.cart.databinding.ActivityOrderConfirmBinding
import com.frxuexi.cart.databinding.PopCouponBinding
import com.frxuexi.lib_base.alipay.MyPay
import com.frxuexi.lib_base.entity.AddressBeanItem
import com.frxuexi.lib_base.entity.CartBeanList
import com.frxuexi.lib_base.entity.CreateOrderReqBean
import com.frxuexi.lib_base.entity.OrderDetail
import com.frxuexi.lib_base.entity.PayOrderReqBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.utils.ArouterManager
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


/**
 * 订单确认页面
 */
@Route(path = "/cart/OrderConfirmActivity")
@AndroidEntryPoint
class OrderConfirmActivity : BaseActivity<ActivityOrderConfirmBinding, CartViewModel>() {

    @Autowired
    lateinit var order: CartBeanList

    @JvmField
    @Autowired
    var cou = 0.0



    @JvmField
    @Autowired
    var yuan = 0.0

    @JvmField
    @Autowired
    var sum = 0.0

    @JvmField
    @Autowired
    var couId = -1

    var isPay=false
    lateinit var address: AddressBeanItem

    val preOrderAdapter by lazy { PreOrderAdapter() }
    val myCouponAdapter by lazy { MyCouponAdapter() }

    var orderNo=""
    var orderId=""

    override fun initData() {
        preOrderAdapter.addData(order.list)
        preOrderAdapter.notifyDataSetChanged()
        binding.conTvsum.setText("共${order.list.size}件商品")
        binding.conSumprice.setText("￥${yuan}")
        binding.conCou.setText("￥${cou}")
        binding.conSum.setText("￥${sum}")

        vm.myCouponData.observe(this) {
            myCouponAdapter.apply {
                data.clear()
                addData(it.list)
                notifyDataSetChanged()
            }
        }

        vm.defaultAddressData.observe(this) {
            address = it
            setAdd(it)
        }

        vm.createOrderData.observe(this) {
            Log.i("lr", it.toString())
            orderNo=it.orderNo
            ToastUtils.showLong("下单成功")
            //删除
            vm.deleteCart(order.list.map { it.id })
            if(isPay){
                MyPay.payV2(sum.toString(),this@OrderConfirmActivity)
            }else{
                ArouterManager.nav(this,"/cart/OrderActivity")
            }

        }

        vm.payOrderData.observe(this){
            ArouterManager.nav(this,"/cart/OrderActivity")
        }

        vm.orderByIdData.observe(this){
            orderId=it.id.toString()
//            支付接口，为了更改订单状态
            val reqBean =
                PayOrderReqBean("", orderNo, "alipay", "yue", 0, orderId)
            vm.payOrder(reqBean)
        }
    }

    fun setAdd(it: AddressBeanItem) {
        binding.conName.setText(it.realName)
        binding.conPhone.setText(it.phone)
        var city =
            "${if (it.province == it.city) it.province else it.province + it.city}${it.district}${it.detail}"
        binding.conAddress.setText(city)
        if (it.isDefault) {
            binding.conMo.visibility = View.VISIBLE
        } else {
            binding.conMo.visibility = View.GONE
        }
    }


    override fun initView() {
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)

//        查询默认地址
        vm.getDefaultAddress()

        binding.conRv.apply {
            adapter = preOrderAdapter
            layoutManager = LinearLayoutManager(this@OrderConfirmActivity)
        }

        binding.conBei.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val length = s!!.length
                binding.conBeinum.apply {
                    setText("${length}/150")
                    if (length == 10) {
                        setTextColor(getColor(com.frxuexi.lib_base.R.color.redfont))
                    } else {
                        setTextColor(getColor(com.frxuexi.lib_base.R.color.black))
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.conTab.apply {
            addTab(newTab().setText("快递配送"), true)
            addTab(newTab().setText("到店自取"))
        }

        binding.conConAddress.setOnClickListener {
            ArouterManager.nav(this, "/cart/AddressListActivity")
        }

        binding.conCommit.setOnClickListener {
//    选择支付：创建订单-支付宝支付-查询订单详情找到订单id-接口支付
//    选择不支付：创建订单
            AlertDialog.Builder(this)
                .setTitle("支付确认")
                .setMessage("立即支付吗？")
                .setPositiveButton("确定支付",object :OnClickListener{
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        createOrder()
                        isPay=true
                    }
                }).setNegativeButton("暂不支付",object :OnClickListener{
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        createOrder()
                    }
                })
                .create().show()


        }

        binding.conChoice.setOnClickListener {
            vm.getMyCoupon()
            val window = PopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            val couponBinding = PopCouponBinding.inflate(LayoutInflater.from(this))
            window.contentView = couponBinding.root
            window.setBackgroundDrawable(BitmapDrawable())
            window.isFocusable = true
            window.setOutsideTouchable(true)

//            window.update()
            val attributes = getWindow().attributes
            attributes.alpha = 0.5f
            getWindow().attributes = attributes

            window.showAtLocation(binding.conCon, Gravity.BOTTOM, 0, 0)
            window.setOnDismissListener {
                val attributes = getWindow().attributes
                attributes.alpha = 1f
                getWindow().attributes = attributes
            }
            couponBinding.couRv.apply {
                adapter = myCouponAdapter
                layoutManager = LinearLayoutManager(this@OrderConfirmActivity)
            }

            myCouponAdapter.addChildClickViewIds(R.id.cou_use)
            myCouponAdapter.setOnItemClickListener { adapter, view, position ->
                val item = myCouponAdapter.data.get(position)
                window.dismiss()
                couId = item.id
                cou = item.money.toDouble()
                sum = yuan - cou
                binding.conCou.setText("￥${cou}")
                binding.conSum.setText("￥${sum}")
            }
        }
    }

    fun createOrder(){
        val bei = binding.conBei.text.toString()

        val list = mutableListOf<OrderDetail>()
        order.list.forEach {
            list.add(
                OrderDetail(
                    address.id,
                    it.productId,
                    couId,
                    bei,
                    emptyList(),
                    "alipay",
                    "yue",
                    address.phone,
                    it.productId,
                    it.cartNum,
                    address.realName,
                    1,
                    0,
                    false
                )
            )
        }

        val item0 = order.list.get(0)
        val reqBean = CreateOrderReqBean(
            address.id,
            item0.productId,
            couId,
            bei,
            list,
            "alipay",
            "yue",
            address.phone,
            item0.productId,
            item0.cartNum,
            address.realName,
            1,
            0,
            false
        )
        vm.createOrder(reqBean)
    }

    @Subscribe
    fun getMsg(msg:String){
        if(msg=="payOk"){
            Log.i("lr",msg)
//查询订单详情找到订单id
            vm.getOrderById(orderNo)

        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        val item = intent?.extras?.getSerializable("address") as AddressBeanItem
        setAdd(item)
        address = item
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}